package com.kma.ncpractice2013.dao;

import com.kma.ncpractice2013.model.PromoCodeType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;
import org.springframework.jdbc.core.RowMapper;

/**
 *
 * @author Illya
 */
public class PromoCodeTypeDAO extends DAO<PromoCodeType>
{
	@Autowired
	DataSource dataSource;
	private JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
    public void create(PromoCodeType type)
    {
        String sql = "INSERT INTO PDOMOCODE_TYPES(ID,DISCOUNT,START_DATE,EXPIRATION_DATE) VALUES (?,?,?,?)";
        jdbcTemplate.update(sql, type.getId(),type.getDiscount(),type.getStartDate(),type.getExpirationDate());
    }

    public void update(PromoCodeType type)
    {
        String sql = "UPDATE PDOMOCODE_TYPES SET DISCOUNT = ?,START_DATE = ?,EXPIRATION_DATE = ? WHERE ID = ?";
        jdbcTemplate.update(sql, type.getDiscount(),type.getStartDate(),type.getExpirationDate());
    }

    public PromoCodeType getById(int id)
    {
        List<PromoCodeType> typesList;
        String sql = "SELECT * FROM PDOMOCODE_TYPES WHERE ID = " + id;
        typesList = jdbcTemplate.query(sql, new PromoCodeTypeRowMapper());
        return typesList.get(0);
    }

    public Collection<PromoCodeType> getAll()
    {
        String sql = "SELECT  * FROM PDOMOCODE_TYPES ";
	    return jdbcTemplate.query(sql, new PromoCodeTypeRowMapper());
    }

    public void deleteById(int id)
    {
        String sql = "DELETE FROM PDOMOCODE_TYPES WHERE ID = " + id;
        jdbcTemplate.update(sql);
    }
    
    private static final class PromoCodeTypeRowMapper implements RowMapper
    {
        public Object mapRow(ResultSet rs, int rowNum) throws SQLException
        {
            PromoCodeType type = new PromoCodeType();
            type.setId(rs.getInt("id"));
            type.setStartDate(rs.getDate("start_date"));
            type.setExpirationDate(rs.getDate("expiration_date"));
            type.setDiscount(rs.getShort("discount"));
            // set relatedPromoCodes?
            return type;
        }
    }
}
